//
//  HRFunChatSelfCell.m
//  Hear
//
//  Created by mac on 2017/11/24.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRFunChatSelfCell.h"
#import "UIButton+SSEdgeInsets.h"
#import "HRCoverTimeModel.h"
#import "Track.h"
#import "HRCoverImageModel.h"
static void *kStatusKVOKey = &kStatusKVOKey;
static void *kDurationKVOKey = &kDurationKVOKey;
static void *kBufferingRatioKVOKey = &kBufferingRatioKVOKey;
@interface HRFunChatSelfCell ()
@property (nonatomic, strong)UIImageView *iconImageView;
@property(nonatomic, strong)UILabel *titleLabel;
@property(nonatomic, strong)UIButton *nickNameLabel;
@property(nonatomic, strong)UILabel *timeLabel;
@property(nonatomic, strong)UIImageView *voiceBackImageView;

@end
@implementation HRFunChatSelfCell

-(void)setChatModel:(HRFunChatModel *)chatModel{
    _chatModel = chatModel;
    
    WeakSelf
//    if (chatModel.UserPictureName.length < 10){
//        [HRCoverImageModel OriginImage:[UIImage imageNamed:chatModel.UserPictureName] scaleToSize:CGSizeMake(75, 75) callBackOriginImage:^(UIImage *originImage) {
//            weakSelf.iconImageView.image = originImage;
//        }];
//        if (chatModel.UserPictureBackgroundColor.length){
//            self.iconImageView.backgroundColor = [UIColor colorWithHexString:chatModel.UserPictureBackgroundColor];
//        }
//    }else{
        [self.iconImageView.layer setImageWithURL:[NSURL URLWithString:chatModel.UserPictureName] placeholder:[UIImage imageNamed:@""]];
//    }
    self.titleLabel.text = chatModel.TopicTitle;
    
    [self.nickNameLabel setTitle:chatModel.NickName forState:0];
    if ([chatModel.Sex intValue] == 1){
        [self.nickNameLabel setImage:[UIImage imageNamed:@"男"] forState:0];
    }else{
        [self.nickNameLabel setImage:[UIImage imageNamed:@"女"] forState:0];
    }
    
    NSDictionary *dic = @{NSFontAttributeName:CustomUIFont(13)};//指定字号
    CGFloat nickNameLabelWidth = [[NSString stringWithFormat:@"%@ ",chatModel.NickName] boundingRectWithSize:CGSizeMake(180, 30)/*计算高度要先指定宽度*/ options:NSStringDrawingUsesLineFragmentOrigin |
                                  NSStringDrawingUsesFontLeading attributes:dic context:nil].size.width;
    self.nickNameLabel.width = nickNameLabelWidth+20;
    [self.nickNameLabel setTitle:[NSString stringWithFormat:@"%@ ",chatModel.NickName] forState:0];
    [self.nickNameLabel setImagePositionWithType:SSImagePositionTypeRight spacing:5];

    
    self.timeLabel.text = chatModel.ActiveText;

    if (chatModel.isPlaying){
        [self.voicImageView startAnimating];
    }else{
        [self.voicImageView stopAnimating];
    }
    if (chatModel.SoundUrl.length){
        self.voiceBackImageView.hidden = NO;
    }else{
        self.voiceBackImageView.hidden = YES;
    }
    
    
}



+(instancetype)cellWithTableView:(UITableView *)tableView
{
    static NSString *cellID = @"HRFunChatSelfCell";
    
    HRFunChatSelfCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if(!cell){
        cell = [[HRFunChatSelfCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    return cell;
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    if (self)
    {
        self.backgroundColor = [UIColor clearColor];
        
        UIImageView *backImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, kFullWidth-20, 70)];
        backImageView.image = [UIImage imageNamed:@"趣聊_矩形"];
        [self addSubview:backImageView];
        backImageView.userInteractionEnabled = YES;
        
        UIImageView *iconImageView = [[UIView alloc] initWithFrame:CGRectMake(0, 7, backImageView.height-14, backImageView.height-14)];
        [backImageView addSubview:(self.iconImageView=iconImageView)];
        iconImageView.backgroundColor = CustomColor(240, 240, 240, 1);
        iconImageView.layer.cornerRadius = iconImageView.width/2;
        iconImageView.clipsToBounds = YES;
        iconImageView.userInteractionEnabled = YES;
        
        
        self.voiceBackImageView = [UIImageView new];
        self.voiceBackImageView.backgroundColor = [UIColor clearColor];
        self.voiceBackImageView.image = [UIImage imageNamed:@"半圆"];
        [backImageView addSubview:self.voiceBackImageView];
        self.voiceBackImageView.frame = CGRectMake(self.iconImageView.left, self.iconImageView.bottom-25, 25, 25);
        self.voiceBackImageView.layer.cornerRadius = self.voiceBackImageView.width/2;
        self.voiceBackImageView.clipsToBounds = YES;
        self.voiceBackImageView.userInteractionEnabled = YES;
        
        self.voicImageView = [UIImageView new];
        self.voicImageView.image = [UIImage imageNamed:@"语音图片_语音气泡5"];
        self.voicImageView.clipsToBounds = YES;
        [self.voiceBackImageView addSubview:self.voicImageView];
        self.voicImageView.userInteractionEnabled = YES;
        self.voicImageView.frame = self.voiceBackImageView.bounds;
        WeakSelf
        UITapGestureRecognizer *voiceImageTap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            [weakSelf playSound];
        }];
        [self.voicImageView addGestureRecognizer:voiceImageTap];
        
        NSArray * animateNames = @[@"语音图片_语音气泡1",@"语音图片_语音气泡2",@"语音图片_语音气泡3",@"语音图片_语音气泡4",@"语音图片_语音气泡5"];
        
        NSMutableArray * animationImages = [[NSMutableArray alloc] initWithCapacity:animateNames.count];
        for (NSString * animateName in animateNames) {
            UIImage * animateImage = [UIImage imageNamed:animateName];
            [animationImages addObject:animateImage];
        }
        self.voicImageView.animationImages = animationImages;
        self.voicImageView.animationDuration = 1.0;
        
        
        
        self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(iconImageView.right+25, 0, backImageView.width -iconImageView.right-25, 35)];
//        self.titleLabel.text = @"异地恋的你们，后来怎么样了？";
        self.titleLabel.font = CustomUIFont(14);
        self.titleLabel.textColor = FirstTextColor;
        [backImageView  addSubview:self.titleLabel];
        
        
        
        UILabel *lineLabel = [UILabel new];
        lineLabel.backgroundColor = CustomColor(240, 240, 240, 1);
        [backImageView  addSubview:lineLabel];
        lineLabel.frame = CGRectMake(iconImageView.right+20, self.titleLabel.bottom, backImageView.width -iconImageView.right-20, 1);
        
        
        self.nickNameLabel = [UIButton buttonWithType:0];
//        [self.nickNameLabel setTitle:@"啦啦啦啦" forState:0];
        [self.nickNameLabel setTitleColor:SecondTextColor forState:0];
        self.nickNameLabel.titleLabel.font = CustomUIFont(13);
        [backImageView addSubview:self.nickNameLabel];
        self.nickNameLabel.frame = CGRectMake(self.titleLabel.left, lineLabel.bottom, 80, self.titleLabel.height);
        self.nickNameLabel.userInteractionEnabled = NO;
        
        
        self.timeLabel = [UILabel new];
//        self.timeLabel.text = @"十分钟前发布";
        self.timeLabel.font = CustomUIFont(13);
        self.timeLabel.textColor = FirstTextColor;
        [backImageView  addSubview:self.timeLabel];
        self.timeLabel.frame = CGRectMake(backImageView.width-90, lineLabel.bottom, 80, self.titleLabel.height);
        self.timeLabel.textAlignment = 2;
        
        
    }
    return self;
}

- (void)playSound{
    if (!self.chatModel.SoundUrl.length){
        [MBProgressHUD showMessage:@"当前音频文件为空" finishBlock:nil];
        return;
    }
    
    
    if (self.chatModel.isPlaying){
        self.chatModel.isPlaying = NO;
        if (self.playMedioBlock){
            self.playMedioBlock(self.chatModel);
        }
        [self.streamer pause];
        
    }else{
        self.chatModel.isPlaying = YES;
        if (self.playMedioBlock){
            self.playMedioBlock(self.chatModel);
        }
        [self createPlayer];
        
    }
}



- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (context == kStatusKVOKey) {
        [self performSelector:@selector(updateStatus)
                     onThread:[NSThread mainThread]
                   withObject:nil
                waitUntilDone:NO];
    } else if (context == kDurationKVOKey) {
        //        [self performSelector:@selector(updateSliderValue:)
        //                     onThread:[NSThread mainThread]
        //                   withObject:nil
        //                waitUntilDone:NO];
    } else if (context == kBufferingRatioKVOKey) {
        //        [self performSelector:@selector(updateBufferingStatus)
        //                     onThread:[NSThread mainThread]
        //                   withObject:nil
        //                waitUntilDone:NO];
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


- (void)updateStatus {
    //    self.musicIsPlaying = NO;
    //    _musicIndicator.state = NAKPlaybackIndicatorViewStateStopped;
    switch ([_streamer status]) {
        case DOUAudioStreamerPlaying:
            break;
            
        case DOUAudioStreamerPaused:
            break;
            
        case DOUAudioStreamerIdle:
            break;
            
        case DOUAudioStreamerFinished:
            [self.voicImageView stopAnimating];
            break;
            
        case DOUAudioStreamerBuffering:
            break;
            
        case DOUAudioStreamerError:
            break;
    }
}



- (void)createPlayer{
    
    
    Track *track = [[Track alloc] init];
    track.audioFileURL = [NSURL URLWithString:self.chatModel.SoundUrl];
    @try {
        [self removeStreamerObserver];
    } @catch(id anException){
    }
    
    
    _streamer = nil;
    _streamer = [DOUAudioStreamer streamerWithAudioFile:track];
    
    [self addStreamerObserver];
    [self.streamer play];
}

- (void)removeStreamerObserver {
    [_streamer removeObserver:self forKeyPath:@"status"];
    [_streamer removeObserver:self forKeyPath:@"duration"];
    [_streamer removeObserver:self forKeyPath:@"bufferingRatio"];
}

- (void)addStreamerObserver {
    [_streamer addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:kStatusKVOKey];
    [_streamer addObserver:self forKeyPath:@"duration" options:NSKeyValueObservingOptionNew context:kDurationKVOKey];
    [_streamer addObserver:self forKeyPath:@"bufferingRatio" options:NSKeyValueObservingOptionNew context:kBufferingRatioKVOKey];
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
